package com.tamecode.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author Liqc
 * @date 2021/8/4 10:04
 */
public class ReflectTest {

    public static void main(String[] args) throws Exception {
        Car car = initByDefaultConst();
        car.introduce();
    }

    public static Car initByDefaultConst() throws Exception {
        // 通过类装载器获取 Car 类对象
        ClassLoader loader = ClassLoader.getSystemClassLoader();
//        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        System.out.println(loader.toString());
        Class<?> clazz = loader.loadClass("com.tamecode.reflect.Car");

        // 获取类的默认构造器对象并通过它实例化 Car，参数是构造器参数的类型
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor((Class[]) null);
        Car car = (Car) declaredConstructor.newInstance();

        // 通过反射方法设置属性
        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "红旗72");
        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "Red");
        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 200);
        Field brand = clazz.getDeclaredField("brand");

        // 允许访问 private protect 的属性，Method 也类似
        brand.setAccessible(true);
        String o = (String) brand.get(car);
        brand.set(car, "长城S6");
        System.out.println(o);
        return car;
    }

}
